package com.example.mplayer.utils

import android.os.Build
import android.util.Base64
import androidx.annotation.RequiresApi
import org.json.JSONObject
import java.security.KeyFactory
import java.security.spec.X509EncodedKeySpec
import java.time.Instant
import javax.crypto.Cipher

object EncryptionUtils {
    private val PUBLIC_KEY = """
        -----BEGIN PUBLIC KEY-----
        MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAqgYgxl44bdCnAoEGXYFR
        LyRZFS/9sdp1Xmhx+XO6ZVkhBAx+yzfHYaWkh10alj0k9WAsppmVUc8xPT3+n9sq
        bQS37uXH2bTftR7p+h/mT7w5/WBSkj2MyeccRtR6Lk/lH9ZLwGndiwjEze3xBcq6
        o7qeBCmKeyupnJeWIviVa/X9H5uAt7ST5yWVlVNG13FSZJzTLC4te9aZMb2JzwHS
        Y1skeU6uV0CME2fWhAwuOzd3ihFActUzmy8Pa7B3S3uXcTJAzwzgkj3nBQYx75fS
        hc6XMckIxMRJqHpnJ1SkWvw2BQwGCE4dwP0yKkGw0VgA9aIbN5hz9kkjnv/SdcQj
        vwIDAQAB
        -----END PUBLIC KEY-----
    """.trimIndent()

    @RequiresApi(Build.VERSION_CODES.O)
    fun encryptKey(key: String): String {
        try {
            // Create JSON data
            val jsonData = JSONObject().apply {
                put("key", key)
                put("timestamp", Instant.now().toString())
            }.toString()

            // Get RSA public key
            val publicKeyPEM = PUBLIC_KEY
                .replace("-----BEGIN PUBLIC KEY-----", "")
                .replace("-----END PUBLIC KEY-----", "")
                .replace("\n", "")
                .trim()

            val keySpec = X509EncodedKeySpec(Base64.decode(publicKeyPEM, Base64.DEFAULT))
            val keyFactory = KeyFactory.getInstance("RSA")
            val publicKey = keyFactory.generatePublic(keySpec)

            // Encrypt data
            val cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding")
            cipher.init(Cipher.ENCRYPT_MODE, publicKey)
            val encryptedBytes = cipher.doFinal(jsonData.toByteArray())

            // Return Base64 encoded string
            return Base64.encodeToString(encryptedBytes, Base64.NO_WRAP)
        } catch (e: Exception) {
            e.printStackTrace()
            throw RuntimeException("Encryption failed: ${e.message}")
        }
    }
}